import { useUserStoreHook } from "@/store/modules/user";
import { addDialog } from "@/components/ReDialog";
import { isLogin } from "./auth";
import { useMessage } from "@/layout/components/lay-notice/data";
const { VITE_PUBLIC_PATH } = import.meta.env;

/**
 * SSE
 */
class SSEClient {
  private eventSource: EventSource | null = null;
  private reconnectCount: number = 0;
  private audio: HTMLAudioElement;
  private url: string = "";
  private _next: boolean = true;
  constructor(url: string) {
    this.url = url;
    this.reconnectCount = 0;
    // 初始化音频对象
    this.audio = new Audio(`${VITE_PUBLIC_PATH}audio/notice_2.mp3`);
  }

  public connect() {
    if (this.eventSource) {
      this.eventSource.close();
    }

    this.eventSource = new EventSource(this.url);

    this.eventSource.onmessage = event => {
      const data = JSON.parse(event.data);
      this.handleMessage(data);
    };

    this.eventSource.onerror = () => {
      if (!isLogin()) return;
      console.log("SSE 连接异常，正在尝试重新连接...");
      this.eventSource?.close();
      this.reconnectCount += 1;
      if (this.reconnectCount <= 3) {
        setTimeout(() => this.connect(), 3000);
      } else {
        console.log("SSE 连接异常，已超过最大重试次数！");
      }
    };
  }

  public disconnect() {
    this.eventSource?.close();
    this.eventSource = null;
  }

  private handleMessage(data: any) {
    // 处理接收到的消息
    switch (data.type) {
      case "message": // 异地登录
        // 播放提示音
        this.audio.play();
        useMessage().addNotify(data.data);
        break;
      case "force": // 强制下线
        useUserStoreHook().logOut();
        addDialog({
          title: "提示",
          center: true,
          showClose: false,
          closeOnPressEscape: false,
          closeOnClickModal: false,
          contentRenderer: () => h("p", data?.msg || "您已被管理员强制下线！")
        });
        break;
      case "logOut": // 异地登录
        useUserStoreHook().logOut();
        addDialog({
          title: "提示",
          center: true,
          showClose: false,
          closeOnPressEscape: false,
          closeOnClickModal: false,
          contentRenderer: () => h("p", data?.msg || "您已被迫下线")
        });
        break;
      default:
        break;
    }
    console.log("Received message:", data);
  }
}

export default SSEClient;
